<template>
  <div class="home" ref="home">
    <header style="border-bottom: 1px solid #ccc;height: 28px;">
      <top-menu></top-menu>
    </header>
    <section class="home-content" ref="homeContent">
      <add-content-button @click.native="openEditorWindow(null)" style="margin-bottom: 10px;"></add-content-button>
      <div style="flex: 1;" @click="isSmallToolsContent = false">
        <content-list :list="list" :lineType="baseSetting.splitLine" @contentItemRightClick="contentItemRightClick"></content-list>
      </div>
    </section>
    <footer style="border-top: 1px solid #ccc;height: 36px;">
      <transition>
        <small-tools-content v-if="isSmallToolsContent">
          <transition mode="out-in">
            <bubble-box v-if="smallToolsListIndex == 0" key="0" direction="bottom" :offset="angleOffset">
              <search-box v-model="searchText" :isOpenRegex="isOpenRegex" @regexButtonClick="isOpenRegex = !isOpenRegex"></search-box>
            </bubble-box>
            <bubble-box v-if="smallToolsListIndex == 1" key="1" direction="bottom" :offset="angleOffset">
              <weather></weather>
            </bubble-box>
            <bubble-box v-if="smallToolsListIndex == 2" key="2" direction="bottom" :offset="angleOffset">
              <skin-select v-model="color" @saveBackgroundColor="saveBackgroundColor"></skin-select>
            </bubble-box>
            <bubble-box v-if="smallToolsListIndex == 3" key="3" direction="bottom" :offset="angleOffset">
              <base-setting v-model="baseSetting" @saveBaseSetting="saveBaseSetting"> </base-setting>
            </bubble-box>
            <bubble-box v-if="smallToolsListIndex == 4" key="4" direction="bottom" :offset="angleOffset">
              <shortcut></shortcut>
            </bubble-box>
          </transition>
        </small-tools-content>
      </transition>
      <small-tools-list class="small-tools" @iconIndexCilck="iconIndexCilck"></small-tools-list>
    </footer>
  </div>
</template>

<script>
import TopMenu from '@/components/topMenu/TopMenu.vue';
import AddContentButton from '@/components/addContentButton/AddContentButton.vue';
import ContentList from '@/components/contentList/ContentList.vue';
import SmallToolsList from '@/components/smallTools/SmallToolsList.vue';
import SmallToolsContent from '@/components/smallTools/SmallToolsContent.vue';
import BubbleBox from '@/components/bubbleBox/BubbleBox.vue';
import SearchBox from '@/components/searchBox/SearchBox.vue';
import SkinSelect from '@/components/skinSelect/SkinSelect.vue';
import Weather from '@/components/weather/Weather.vue';
import BaseSetting from '@/components/baseSetting/BaseSetting.vue';
import Shortcut from '@/components/shortcut/Shortcut.vue';

const { ipcRenderer } = window.electron;
export default {
  name: 'Home',
  data() {
    return {
      // 主要内容
      list: [],
      // 小工具栏
      smallToolsListIndex: 0,
      isSmallToolsContent: false,
      angleOffset: 10,
      // 搜索框
      searchText: '',
      isOpenRegex: false,
      // 背景颜色
      color: {
        r: 0,
        g: 0,
        b: 0,
        a: 0.6,
      },
      // 基础设置: 字体,字体类型,字体大小
      baseSetting: {
        splitLine: 'solid',
        fontSize: 14,
        fontFamily: '仿宋',
      },
    };
  },
  components: {
    TopMenu,
    AddContentButton,
    ContentList,
    SmallToolsList,
    SmallToolsContent,
    Weather,
    BubbleBox,
    SkinSelect,
    BaseSetting,
    SearchBox,
    Shortcut
  },
  created() {
    // 接收主线程发过来的消息(右键菜单)
    ipcRenderer.on('message', ({ text, id }) => {
      try {
        switch (text) {
          case 'editorSave':
            this.list = this.getList('desc');
            this.isSmallToolsContent = false;
            break;
          case '完成':
            this.updateListItem(id, { isComplete: true });
            this.list = this.getList('desc');
            break;
          case '取消完成':
            this.updateListItem(id, { isComplete: false });
            this.list = this.getList('desc');
            break;
          case '编辑':
            this.openEditorWindow(id);
            break;
          case '删除':
            let res = confirm('你确定要删除吗?'); //在页面上弹出对话框
            if (res) {
              this.removeListItem(id);
              this.closeEditorWindow(id);
              this.list = this.getList('desc');
            }
            break;

          default:
            break;
        }
      } catch (error) {
        console.log(error);
      }
    });
  },
  mounted() {
    // 更新数据
    const userCollection = this.db('user');
    this.list = this.getList('desc');
    this.color = userCollection.get('backgroundColor').value();
    this.baseSetting = userCollection.get('baseSetting').value();
  },
  watch: {
    color(newValue) {
      let { r, g, b, a } = newValue;
      this.$refs.home.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a})`;
    },
    baseSetting(newValue) {
      this.$refs.home.style.fontFamily = newValue.fontFamily;
      this.$refs.homeContent.style.fontSize = newValue.fontSize + 'px';
    },
    searchText(newValue) {
      if (this.isOpenRegex) {
        this.list = newValue ? this.findDataRegex(eval('/' + newValue + '/')) : this.getList('desc');
      } else {
        this.list = newValue ? this.findData(newValue) : this.getList('desc');
      }
    },
    isOpenRegex(newValue) {
      if (newValue) {
        this.list = this.searchText ? this.findDataRegex(eval('/' + this.searchText + '/')) : this.getList('desc');
      } else {
        this.list = this.searchText ? this.findData(this.searchText) : this.getList('desc');
      }
    },
    isSmallToolsContent(newValue) {
      !newValue && this.restoreSettting();
    },
    smallToolsListIndex(newValue) {
      this.restoreSettting();
    },
  },
  methods: {
    /**
     * 重复代码写成方法
     */
    restoreSettting() {
      // 如何用户没有点确定,还原设置
      const userCollection = this.db('user');
      this.searchText = '';
      this.color = userCollection.get('backgroundColor').value();
      this.baseSetting = userCollection.get('baseSetting').value();
    },
    /**
     * 事件
     */
    iconIndexCilck(e) {
      this.isSmallToolsContent = e.index == this.smallToolsListIndex ? !this.isSmallToolsContent : true;
      this.smallToolsListIndex = e.index;
      this.angleOffset = e.angleOffset;
    },
    saveBackgroundColor() {
      this.db('user')
        .assign({ backgroundColor: this.color })
        .write();
      this.isSmallToolsContent = false;
    },
    saveBaseSetting() {
      this.db('user')
        .assign({ baseSetting: this.baseSetting })
        .write();
      this.isSmallToolsContent = false;
    },
    /**
     * 线程通信
     */
    closeEditorWindow(id) {
      ipcRenderer.send('editorWindow', { message: 'close', key: id });
    },
    openEditorWindow(id = null) {
      id ? ipcRenderer.send('editorWindow', { message: 'edit', id: id }) : ipcRenderer.send('editorWindow', { message: 'add' });
    },
    contentItemRightClick(item) {
      ipcRenderer.send('mainWindow', { message: 'contextMenu', id: item.id ,isComplete: item.isComplete});
    },
    /**
     * 获取数据
     */
    removeListItem(id) {
      this.updateListItem(id, {status: -1});
    },
    updateListItem(id, obj) {
      const collection = this.db('data').get('RECORDS');
      collection.updateById(id, obj).write();
    },
    getList(sortType) {
      const collection = this.db('data').get('RECORDS');
      return collection.filter(item => item.status !== -1).orderBy('time', sortType).value();
    },
    findData(str) {
      const collection = this.db('data').get('RECORDS').filter((item) => item.status !== -1);
      return [
        ...collection
          .filter((item) => {
            return item.title.indexOf(str) != -1;
          })
          .orderBy('time', 'desc')
          .value(),
        ...collection
          .filter((item) => {
            return item.title.indexOf(str) == -1 && item.text.indexOf(str) != -1;
          })
          .orderBy('time', 'desc')
          .value(),
      ];
    },
    findDataRegex(regex) {
      const collection = this.db('data').get('RECORDS').filter((item) => item.status !== -1);
      return [
        ...collection
          .filter((item) => {
            return regex.test(item.title);
          })
          .orderBy('time', 'desc')
          .value(),
        ...collection
          .filter((item) => {
            return !regex.test(item.title) && regex.test(item.text);
          })
          .orderBy('time', 'desc')
          .value(),
      ];
    },
  },
};
</script>

<style scoped>
.home {
  width: 99.6%;
  height: 99.6%;
  color: #fff;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;

  background-color: rgba(0, 0, 0, 0.5);
}
.home-content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

/* 进入前和结束后的状态 */
.v-enter,
.v-leave-to {
  opacity: 0;
}
/* 进入和离开的动画时间段 */
.v-enter-active,
.v-leave-active {
  transition: all 0.4s ease;
}
</style>
